import { ProForm, ProFormRadio, ProFormText } from "@ant-design/pro-components"
import ProFormDept from "../../dept/modules/proFormDept";
import { useDictOptions } from "@/hooks";
import { getUser, addUser, updateUser, checkUserNameUnique, checkPhoneUnique } from '@/api/system/user'

const UserForm = ({ userId }) => {
  const { data: options } = useDictOptions('user_status')
  const checkUserName = async (_, value) => {
    const msg = '用户名称已存在'
    if (value === '') {
      return Promise.resolve()
    } else {
      const checkData = {
        userName: value,
        id: userId
      }
      const response = await checkUserNameUnique(checkData)
      if (response.data.code === '1') {
        return Promise.resolve()
      } else {
        return Promise.reject(msg)
      }
    }
  }

  const checkPhone = async (_, value) => {
    const msg = '手机号已存在'
    if (value === '') {
      return Promise.resolve()
    } else {
      const checkData = {
        phonenumber: value,
        id: userId
      }
      const response = await checkPhoneUnique(checkData)
      if (response.data.code === '1') {
        return Promise.resolve()
      } else {
        return Promise.reject(msg)
      }
    }
  }

  return <>
    <ProForm.Group rowProps={{
      gutter: 20
    }}>

      <ProForm.Item name='id' hidden></ProForm.Item>
      <ProForm.Item name='version' hidden></ProForm.Item>

      <ProFormText
        colProps={{ lg: 12, md: 12, sm: 24 }}
        name="name"
        label="姓名"
        placeholder="请输入姓名"
        rules={[{ required: true, message: '请输入姓名' }]}
      />

      <ProFormText
        colProps={{ lg: 12, md: 12, sm: 24 }}
        name="userName"
        label="用户名"
        placeholder="请输入用户名"
        rules={[{ required: true, message: '请输入用户名' }, { validator: checkUserName, validateTrigger: 'onBlur' }]}
      />
      <ProFormDept
        colProps={{ lg: 12, md: 12, sm: 24 }}
        name="deptId"
        label="组织"
        placeholder="请选择组织"
        rules={[{ required: true, message: '请选择组织' }]}
      />

      <ProFormText
        colProps={{ lg: 12, md: 12, sm: 24 }}
        name="email"
        label="邮箱地址"
        placeholder="请输入邮箱地址"
      />

      <ProFormText
        colProps={{ lg: 12, md: 12, sm: 24 }}
        name="phonenumber"
        label="手机号"
        placeholder="请输入手机号"
        rules={[
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请正确填写手机号',
            trigger: 'blur'
          },
          { validator: checkPhone, validateTrigger: 'onBlur' }
        ]}
      />

      <ProFormRadio.Group
        colProps={{ lg: 12, md: 12, sm: 24 }}
        label="状态"
        name="status"
        fieldProps={{
          optionType: "button",
          buttonStyle: "solid"
        }}
        options={options}
      />

    </ProForm.Group>
  </>
}

export default UserForm